package cn.bellychang.leetcode.question019;

/**
 * @author ChangLiang
 * @date 2021/3/8
 */
public class Solution3 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode prev = null;
        ListNode curr = head;
        if(isNthNode(head, n)){
            head = head.next;
            return head;
        }
        while(!isNthNode(curr, n)){
            prev = curr;
            curr = curr.next;
        }
        prev.next = curr.next;
        return head;
    }

    private boolean isNthNode(ListNode node, int n){
        int count = 0;
        while(node!=null){
            count++;
            node = node.next;
        }
        return count==n;
    }
}
